package toOffer;

/**
 * @author YuanAo
 * @date 2024/7/2 14:49
 * @description 删除链表中的重复元素
 */

/**
 * 题目：给定一个已排序的链表的头 head ，删除所有重复的元素，使每个元素只出现一次 。返回已排序的链表 。
 */
public class No83 {
    public static void main(String[] args) {
        int[] head = {1, 1, 2, 3, 3};
        ListNode listNode = null;
        for (int i = head.length - 1; i >= 0; i--) {
            if (i == head.length - 1){
                listNode = new ListNode(head[i]);
            }
            listNode = new ListNode(head[i], listNode);
        }
        ListNode node = deleteDuplicates(listNode);
        while (node != null){
            System.out.print(node.val + " ");
            node = node.next;
        }
    }

    /**
     * 思路：傻卵题
     * @param head
     * @return
     */
    public static ListNode deleteDuplicates(ListNode head) {
        if (head == null){
            return null;
        }

        // 必须tn等于head不能等于head.next，不然第一个和第二个节点不会进行比较
        ListNode tn = head;
        while (tn.next != null){
            if (tn.val == tn.next.val){
                tn.next = tn.next.next;
            }else {
                tn = tn.next;
            }
        }

        return head;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public ListNode getNext() {
            return next;
        }

        public void setNext(ListNode next) {
            this.next = next;
        }
    }
}
